﻿using Newtonsoft.Json;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;

namespace HobSoft.SoccerBet2014.Domain.Common.BfApi
{
    public abstract class ApiRestClient
    {
        protected abstract string EndPoint { get; }
        protected HttpClient RequestClient;
        public string LastResponseResult { get; protected set; }

        public ApiRestClient(string key, string token)
        {
            RequestClient = new HttpClient();
            RequestClient.DefaultRequestHeaders.Add("X-Application", key);
            RequestClient.DefaultRequestHeaders.Add("X-Authentication", token);
            RequestClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
            RequestClient.DefaultRequestHeaders.AcceptCharset.Add(new StringWithQualityHeaderValue("UTF-8"));
        }

        public async virtual Task<string> PostAsync(string method, ApiJsonContent content)
        {
            var url = CreatePostUrl(method);
            var response = await RequestClient.PostAsync(url, content);
            response.EnsureSuccessStatusCode();
            var result = await response.Content.ReadAsStringAsync();
            LastResponseResult = result;
            if (result.Contains("exception"))
                ThrowException(JsonConvert.DeserializeObject<ApiError>(result));
            return result;
        }

        protected virtual void ThrowException(ApiError error)
        {
            var data = error.Data;
            var exceptionName = data.Property("exceptionname").Value.ToString();
            var exceptionData = data.Property(exceptionName).Value.ToString();
            var exception = JsonConvert.DeserializeObject<APINGException>(exceptionData);
            throw exception;
        }

        protected virtual string CreatePostUrl(string method)
        {
            if (EndPoint.EndsWith("/"))
                return EndPoint + method + "/";
            else
                return EndPoint + "/" + method + "/";
        }
    }
}
